package com.fc.base.support;

import java.sql.Connection;
import java.sql.SQLException;

import com.fc.base.DBUtil.DBUtil;
import com.fc.base.DBUtil.JDBConnection;
import com.fc.util.file.XmlUtil;

public class DBConnectSupervisor {
	private static ThreadLocal<Connection> connectionManage = new ThreadLocal<Connection>();
	// 事务手动开关
	private static ThreadLocal<Boolean> transaction = new ThreadLocal<Boolean>() {
		@Override
		protected Boolean initialValue() {
			return false;
		}

	};
	private final static String jndi_driver = XmlUtil.getValue("jndi",
			"sysConfig");

	public static Connection getConnectionManage() throws SQLException {
		Connection conn = connectionManage.get();
		if (null == conn) {
			if ("1".equals(jndi_driver))
				conn = DBUtil.getConnection();
			else
				conn = JDBConnection.getConnection();
			conn.setAutoCommit(false);
			setConnectionManage(conn);
		}
		return connectionManage.get();
	}

	public static void setConnectionManage(Connection conn) {
		connectionManage.set(conn);
	}

	// 一个事务开关对应一个connection
	public static void closeConnection() {
		if (getAutoCommit()) {
			Connection conn = connectionManage.get();
			if (null != conn)
				if ("1".equals(jndi_driver))
					DBUtil.closeConn(conn);
				else
					JDBConnection.closeConn(conn);
			connectionManage.remove();
			transaction.remove();
		}
	}

	public static void setAutoCommit(boolean flag) {
		transaction.set(flag);
	}

	public static boolean getAutoCommit() {
		return transaction.get();
	}

	public static void commit() throws SQLException {
		connectionManage.get().commit();
	}

	public static void rollback() throws SQLException {
		connectionManage.get().rollback();
	}
}
